<!-- src/layouts/Sidebar.vue -->
<template>
  <div class="sidebar-wrapper">
    <el-scrollbar class="sidebar-scrollbar">
      <el-menu
        :default-active="activeMenu"
        :collapse="!appStore.sidebar.opened"
        :collapse-transition="false"
        :unique-opened="false"
        router
        class="sidebar-menu"
      >
        <template v-for="route in menuRoutes" :key="route.path">
          <!-- 混合模式：只显示一级菜单，扁平化 -->
          <template v-if="appStore.settings.Layout === 'mix'">
            <el-menu-item 
              v-if="!route.children || route.children.length === 0"
              :index="route.path"
            >
              <el-icon v-if="route.meta?.icon">
                <component :is="getIconComponent(route.meta.icon)" />
              </el-icon>
              <span>{{ route.meta?.title }}</span>
            </el-menu-item>
            <!-- 有子菜单的父级菜单：使用唯一的 index 并手动处理导航 -->
            <el-menu-item 
              v-else
              :index="`mix-parent-${route.path}`"
              @click="(e) => handleMixMenuClick(route, e)"
            >
              <el-icon v-if="route.meta?.icon">
                <component :is="getIconComponent(route.meta.icon)" />
              </el-icon>
              <span>{{ route.meta?.title }}</span>
            </el-menu-item>
          </template>
          <!-- 垂直模式：正常显示多级菜单 -->
          <template v-else>
            <sidebar-item :route="route" :base-path="''" />
          </template>
        </template>
      </el-menu>
    </el-scrollbar>
    
    <!-- 折叠/展开按钮 -->
    <div class="sidebar-toggle" @click="toggleSidebar" :class="{ 'is-collapsed': !appStore.sidebar.opened }">
      <el-icon class="toggle-icon">
        <DArrowLeft v-if="appStore.sidebar.opened" />
        <DArrowRight v-else />
      </el-icon>
      <span v-if="appStore.sidebar.opened" class="toggle-text">收起菜单</span>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useAppStore } from "@/store/app";
import { useUserStore } from "@/store/user";
import { DArrowLeft, DArrowRight } from '@element-plus/icons-vue';
import SidebarItem from "./SidebarItem.vue";
import * as ElementPlusIconsVue from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const appStore = useAppStore();
const userStore = useUserStore();

// 强制刷新标志
const refreshKey = ref(0);

// 切换侧边栏
const toggleSidebar = () => {
  appStore.toggleSidebar();
};

// 获取图标组件
const getIconComponent = (iconName) => {
  if (!iconName) return ElementPlusIconsVue.Document;
  const componentName = iconName
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join('');
  return ElementPlusIconsVue[componentName] || ElementPlusIconsVue.Document;
};

// 处理混合模式菜单点击
const handleMixMenuClick = (route, event) => {
  // 阻止 el-menu 的默认路由行为
  if (event) {
    event.preventDefault?.();
    event.stopPropagation?.();
  }
  
  if (route.children && route.children.length > 0) {
    // 如果有子菜单，构建完整路径并导航到第一个子菜单
    const childPath = route.children[0].path;
    // 如果子路由path是绝对路径，直接使用；否则拼接父路由path
    const fullPath = childPath.startsWith('/') 
      ? childPath 
      : `${route.path}/${childPath}`.replace(/\/+/g, '/');
    router.push(fullPath);
  } else {
    // 如果没有子菜单，导航到父路由
    router.push(route.path);
  }
};

// 获取激活的菜单
const activeMenu = computed(() => {
  const { path } = route;
  // 混合模式：激活一级菜单
  if (appStore.settings.Layout === 'mix') {
    const routes = router.getRoutes();
    const rootRoute = routes.find(r => r.path === '/');
    if (rootRoute && rootRoute.children) {
      for (const child of rootRoute.children) {
        if (path === child.path || path.startsWith(child.path + '/')) {
          // 如果是有子菜单的父路由，返回特殊的 index
          if (child.children && child.children.length > 0) {
            return `mix-parent-${child.path}`;
          }
          return child.path;
        }
      }
    }
  }
  return path;
});

// 监听用户动态路由变化，强制刷新侧边栏
watch(() => userStore.dynamicRoutes, () => {
  refreshKey.value++;
}, { deep: true });

// 获取菜单路由（从路由表中获取已添加的动态路由）
const menuRoutes = computed(() => {
  // 依赖刷新标志
  refreshKey.value;
  
  // 从路由表中查找根路由
  const routes = router.getRoutes();
  const rootRoute = routes.find(r => r.path === '/');
  
  if (!rootRoute || !rootRoute.children) {
    return [];
  }
  
  // 过滤掉隐藏的菜单项，并按 sort 排序
  const visibleRoutes = rootRoute.children.filter((child) => !child.meta?.hidden);
  
  // 根据 meta.sort 排序（已经在权限过滤时设置）
  return visibleRoutes.sort((a, b) => {
    const sortA = a.meta?.sort ?? 999;
    const sortB = b.meta?.sort ?? 999;
    return sortA - sortB;
  });
});
</script>

<style scoped>
.sidebar-wrapper {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  width: 100%;
  overflow: hidden;
}

.sidebar-scrollbar {
  flex: 1;
  overflow: hidden;
  width: 100%;
  min-height: 0; /* 防止flex子元素溢出 */
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden !important;
  max-width: 100%;
}

:deep(.el-scrollbar__view) {
  width: 100% !important;
  max-width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

/* 彻底禁用横向滚动条 */
:deep(.el-scrollbar__bar.is-horizontal) {
  display: none !important;
}

.sidebar-menu {
  border-right: none;
  background: transparent;
  width: 100% !important;
  max-width: 100%;
  overflow: hidden;
}

/* 折叠按钮 - 扁平化设计 */
.sidebar-toggle {
  height: 48px;
  display: flex;
  align-items: center;
  gap: 8px;
  border-top: 1px solid #e8eaed;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #606266;
  background: #ffffff;
  width: 100%;
  flex-shrink: 0;
  padding: 0 20px;
  position: relative;
  margin: 0;
}

.sidebar-toggle:hover {
  background: #f5f7fa;
  color: var(--el-color-primary);
}

.toggle-icon {
  font-size: 20px;
  transition: all 0.2s ease;
  flex-shrink: 0;
  line-height: 1;
}

.sidebar-toggle:hover .toggle-icon {
  transform: translateX(-2px);
}

/* 收起状态下的图标样式 */
.sidebar-toggle.is-collapsed {
  justify-content: center;
  align-items: center;
  padding: 0;
  height: 48px;
}

.sidebar-toggle.is-collapsed .toggle-icon {
  font-size: 18px;
  line-height: 1;
}

.toggle-text {
  font-size: 13px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: color 0.2s ease;
  flex: 1;
}

.sidebar-toggle:hover .toggle-text {
  color: var(--el-color-primary);
}

/* 切换按钮激活状态 */
.sidebar-toggle:active {
  transform: scale(0.98);
}

.sidebar-toggle:active .toggle-icon {
  transform: scale(0.95);
}

/* 浅色主题菜单样式 */
:deep(.el-menu) {
  background: transparent;
  width: 100% !important;
  overflow: hidden;
}

:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  color: #606266;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  margin: 3px 10px;
  padding: 0 16px !important;
  border-radius: 8px;
  height: 46px;
  line-height: 46px;
  font-size: 14px;
  box-sizing: border-box;
  max-width: calc(100% - 20px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  position: relative;
  font-weight: 400;
}

/* 添加左侧激活指示条 */
:deep(.el-menu-item::before) {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 0;
  background: var(--el-color-primary);
  border-radius: 0 2px 2px 0;
  transition: height 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  background: #f5f5f5 !important;
  color: #303133;
}

:deep(.el-menu-item.is-active) {
  background: var(--el-color-primary) !important;
  color: #ffffff !important;
  font-weight: 500;
}

/* 激活状态隐藏左侧指示条 */
:deep(.el-menu-item.is-active::before) {
  display: none;
}

:deep(.el-menu-item .el-icon),
:deep(.el-sub-menu__title .el-icon) {
  color: #909399;
  font-size: 18px;
  margin-right: 10px;
  transition: color 0.15s ease;
}

:deep(.el-menu-item.is-active .el-icon) {
  color: #ffffff !important;
  transition: none;
}

:deep(.el-menu-item:hover .el-icon),
:deep(.el-sub-menu__title:hover .el-icon) {
  color: #303133;
}

/* 子菜单样式 */
:deep(.el-sub-menu .el-menu) {
  background: #f8f9fa;
}

:deep(.el-sub-menu .el-menu-item) {
  padding: 0 16px 0 40px !important;
  min-width: auto;
  box-sizing: border-box;
  max-width: calc(100% - 16px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-sub-menu__icon-arrow) {
  color: #5f6368;
  transition: all 0.3s ease;
}

:deep(.el-sub-menu.is-opened .el-sub-menu__icon-arrow) {
  color: #202124;
}

/* 收起状态样式 */
:deep(.el-menu--collapse) {
  width: 100% !important;
  max-width: 100%;
}

:deep(.el-menu--collapse .el-menu-item),
:deep(.el-menu--collapse .el-sub-menu__title) {
  padding: 0 !important;
  margin: 4px auto;
  width: 48px;
  height: 48px;
  line-height: 48px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}

:deep(.el-menu--collapse .el-menu-item .el-icon),
:deep(.el-menu--collapse .el-sub-menu__title .el-icon) {
  margin: 0 !important;
  font-size: 20px;
}

:deep(.el-menu--collapse .el-menu-item span),
:deep(.el-menu--collapse .el-sub-menu__title span) {
  display: none;
}

:deep(.el-menu--collapse .el-sub-menu__icon-arrow) {
  display: none;
}

:deep(.el-menu--collapse .el-menu-item.is-active) {
  width: 48px;
}

/* 收起状态下的切换按钮 */
:deep(.el-menu--collapse) + .sidebar-toggle {
  height: 48px;
  padding: 0 8px;
}

:deep(.el-menu--collapse) + .sidebar-toggle .toggle-icon {
  font-size: 18px;
}

:deep(.el-menu--collapse) + .sidebar-toggle .toggle-text {
  display: none;
}

/* 滚动条美化 */
:deep(.el-scrollbar__thumb) {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

:deep(.el-scrollbar__thumb:hover) {
  background: rgba(0, 0, 0, 0.15);
}
</style>
